package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.permission.RequireLogin;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查校验
 */
public class CheckLoginInterceptor implements HandlerInterceptor {


   @Autowired
   private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决跨域问题
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断映射方法上是否有贴@RequireLogin注解
        HandlerMethod hm=(HandlerMethod) handler;
        String token = request.getHeader("token");
        //根据token 获取user对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //有该注解进行登录校验
        if (hm.hasMethodAnnotation(RequireLogin.class)) {
            if (user == null) {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        /*String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        if (user==null){
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }*/
        return true;
    }
}
